﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Common;
using System.Text.RegularExpressions;
using System.Globalization;
using Enterprise.Logging;
using System.Reflection;
using System.Data.SqlClient;
using System.Data;
using System.Threading;

namespace Enterprise.Data
{
    public static class DLinqPersistenceHelper
    {
        // Methods
        public static int DeleteByQueryHelper(DataContext dataContext, IQueryable matchingResults, bool physicalDeletion)
        {
            int num = 0;
            DbCommand command = dataContext.GetCommand(matchingResults);
            Match match = new Regex(@"^SELECT[\s]*(?<Fields>.*)[\s]*FROM[\s]*(?<Table>.*)[\s]*AS[\s]*(?<TableAlias>.*)[\s]*WHERE[\s]*(?<Condition>.*)", RegexOptions.IgnoreCase).Match(command.CommandText);
            if (!match.Success)
            {
                throw new ArgumentException("Cannot delete this type of collection.");
            }
            string newValue = match.Groups["Table"].Value.Trim();
            string oldValue = match.Groups["TableAlias"].Value.Trim();
            string str3 = match.Groups["Condition"].Value.Trim().Replace(oldValue, newValue);
            try
            {
                if (physicalDeletion)
                {
                    command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE {1}", new object[] { newValue, str3 });
                }
                else
                {
                    command.CommandText = string.Format(CultureInfo.InvariantCulture, "UPDATE {0} SET StatusId = '{1}', UpdBy = '{2}', UpdAt = '{3}' WHERE {4}", new object[] { newValue, "StatusInactive", ResolveUsername(), DateTime.UtcNow, str3 });
                }
            }
            catch (Exception exception)
            {
                Logger.Error(null, MethodBase.GetCurrentMethod().Name, exception.ToString());
            }
            if (command.Connection.State != ConnectionState.Open)
            {
                command.Connection.Open();
            }
            try
            {
                num = command.ExecuteNonQuery();
            }
            catch (Exception exception2)
            {
                Logger.Error(null, MethodBase.GetCurrentMethod().Name, exception2.ToString());
            }
            return num;
        }

        internal static bool IsConnectionValid(string connection)
        {
            try
            {
                using (SqlConnection connection2 = new SqlConnection(connection))
                {
                    connection2.Open();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

        
        internal static string ResolveUsername()
        {
            //if (AppSession.Enabled && (AppSession.Current != null))
            //{
            //    return AppSession.Current.User.Identity.Name;
            //}
            return Thread.CurrentPrincipal.Identity.Name;
        }
    }


}
